home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!netnews
- From: miker3@ix.netcom.com (Mike Rubenstein)
- Newsgroups: comp.lang.c++
- Subject: Re: novice question on copy constru
- Date: Sun, 28 Jan 1996 13:14:14 GMT
- Organization: Netcom
- Message-ID: <310b743f.135769536@nntp.ix.netcom.com>
- References: <4efpie$jsq@news.ust.hk>
- NNTP-Posting-Host: ix-dc7-18.ix.netcom.com
- X-NETCOM-Date: Sun Jan 28 5:13:57 AM PST 1996
- X-Newsreader: Forte Agent .99c/16.141
-
- ee_ckmaa@uxmail.ust.hk (Chan Ka Ming) wrote:
-
- > I don't understand why one should create a copy constructor. Doesn't the
- > computer will do the job for you when pass arguments by value? Thanks
-
- The compiler will supply a copy constructor, but in many cases in will
- not do so correctly. Consider
-
- class A {
- private:
- char* str;
- public:
- A(const char* s) : str(new char[strlen(s) + 1])
- { strcpy(str, s); }
- ~A() { delete[] str; }
- }
-
- void f(A);
-
- void g()
- {
- A a;
- f(a);
- // ...
- }
-
- The default copy constructor does a memberwise copy. The copy of a
- that is sent to f will contain a pointer to the same string as the
- original a. When it is destroyed, the string will be deleted, but a
- is still active. When a is later destroyed, the string will be
- deleted again. Nothing good happens when you delete an object twice.
-
-
- Michael M Rubenstein
-